package jude.java.money.batch.task;

import static jude.java.money.batch.Definition.FAILURE;
import static jude.java.money.batch.Definition.SUCCESS;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jude.java.money.batch.Keys;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.task.expand.UpdateCodeTask;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.lang.StringUtils;

/**
 * 批量增加或修改文件
 * */
public class BatchUpload extends BatchTask<String[][]> implements UpdateCodeTask {
	
	public BatchUpload(Parameter<String[][]> p) {
		super(p);
	}
	
	private String getCode(boolean overwrite, boolean template) {
		return "$file=$_FILES['file'];\r\n"+
		"if ($file['error'] > 0)\r\n"+
		"	die($file['error']);\r\n"+
		"$path=get_path($_POST['path']);\r\n"+
		(overwrite?"":"if(file_exists($path))die('exists');\r\n")+
		"if(!file_exists(dirname($path)))\r\n"+
		"	if(!mkdir(dirname($path),0777,true))die('no-mkdir');\r\n"+
//		"echo $path;" +
		"if(file_exists($path) && !is_writable($path))\r\n"+
		"	die('no-writable');\r\n"+
//		"if(!file_exists($path) && !is_writable(dirname($path)))\r\n" +
//		"	die('no-writable2');\r\n"+
		"if(!file_exists($file['tmp_name']))die('tmp_name');" +
		"if(move_uploaded_file($file['tmp_name'],$path))\r\n"+
		"	die('"+SUCCESS+"');\r\n"+
		"else\r\n" +
		"	die('"+FAILURE+"');\r\n"+
		"function get_path($path){\r\n"+
		(template?"$tpl=get_template_dir();" +
		"	if(!$tpl)die('cant-get-tpl-name');" +
		"	$path = str_replace('"+Keys.TEMPLATE+"', $tpl, $path);\r\n":"")+
		"	return $path;\r\n"+
		"}\r\n"+
		"\r\n"+
		(template?"function get_template_dir(){\r\n"+
		"	$sql = \"select template_dir from \" . DB_PREFIX . \"template_select where template_language=0\";\r\n"+
		"	$con = mysql_connect(DB_SERVER,DB_SERVER_USERNAME,base64_decode(DB_SERVER_PASSWORD));\r\n"+
		"	mysql_select_db(DB_DATABASE,$con);\r\n"+
		"	$rst = mysql_query($sql,$con);\r\n"+
		"	$row = mysql_fetch_array($rst);\r\n"+
		"	return $row['template_dir'];\r\n"+
		"}":"");
	}
	
	@Override
	protected String getLabel() {
		return "UPL";
	}
	
//	@Override
//	protected boolean checkReadonly() {
//		return true;
//	}
	
//	@Override
//	protected boolean skipSameCode() {
//		return true;
//	}
	
	protected void execute(String site, String url, int group, int index) throws IOException {
		HttpClient client = getHttpClient();
		List<Part> params = new ArrayList<Part>();
		StringPart key = new StringPart("key", P.KEY);
		String[][] uploads = P.PARAMS;
		for (int i = 0; i < uploads.length; i++) {
//			print("\r\n").print(i+1).print("\t");
			params.clear();
			params.add(key);
			String path = uploads[i].length <= 1 ? null : uploads[i][1];
			boolean tpl = false;
			if (StringUtils.isEmpty(path))
				path = StringUtils.replaceChars(uploads[i][0], '\\', '/');
			else
				tpl = path.contains(Keys.TEMPLATE);
			if (!path.startsWith("/"))
				path = "./" + path;
			File file = new File(getLocalPath(uploads[i][0]));
			if (!file.isFile()) {
				L.result(i, "local-not-exists");
				continue;
			}
			params.add(new StringPart("path", path));
			String code = getCode(P.FLAG!=1, tpl);	//默认覆盖文件
			params.add(new StringPart("value", code));
			try {
				PostMethod post = getPostMethod(url, null);
				params.add(new FilePart("file", file));
				Part[] parts = params.toArray(new Part[params.size()]);//{ new FilePart("file", file) };
				post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
				shieldPost(i, site, client, post);
			} catch (FileNotFoundException e) {
			}
		}
	}
	
	@Override
	protected void createPatch() {
		String[][] params = P.PARAMS;
		for (int i = 0; i < params.length; i++) {
			createPatch(params[i][0]);
		}
	}
}
